package org.openwebtop.sunshine.subversion;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openwebtop.sunshine.domain.CodeRepository;
import org.springframework.stereotype.Component;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.BasicAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.wc.SVNClientManager;

@Component
public class SVNRepositoryFactory {
	private final static Log LOG = LogFactory.getLog(SVNRepositoryFactory.class);
	private SVNClientManager manager = SVNClientManager.newInstance();

	@PostConstruct
	public void init() {
		if (LOG.isDebugEnabled()) {
			LOG.debug("SVNRepositoryFactory has been initialized.");
		}

		DAVRepositoryFactory.setup();
		SVNRepositoryFactoryImpl.setup();
		FSRepositoryFactory.setup();
	}

	@PreDestroy
	public void dispose() {
		if (LOG.isDebugEnabled()) {
			LOG.debug("SVNRepositoryFactory has been destroyed.");
		}

		manager.dispose();
	}

	public SVNRepository getRepository(CodeRepository codeRepository) throws Exception {
		if (codeRepository != null) {
			final SVNURL url = SVNURL.parseURIEncoded(codeRepository.getLocation());
			final ISVNAuthenticationManager authManager = new BasicAuthenticationManager(codeRepository.getUsername(), codeRepository.getPassword());

			manager.setAuthenticationManager(authManager);

			if (LOG.isDebugEnabled()) {
				LOG.debug(String.format("Repository pool has been created. (%s)", url));
			}

			return manager.createRepository(url, true);
		}

		return null;
	}
}
